package com.company.emallbackend.task;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.company.emallbackend.entity.Order;
import com.company.emallbackend.entity.ProductOrder;
import com.company.emallbackend.entity.dto.CartDTO;
import com.company.emallbackend.exception.CommonException;
import com.company.emallbackend.mapper.OrderMapper;
import com.company.emallbackend.service.IOrderService;
import com.company.emallbackend.service.IProductOrderService;
import com.company.emallbackend.service.impl.OrderServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author hanlijian
 * @create 2023-01-20-22:37
 */
@Component
@Slf4j
@Transactional(rollbackFor = {})
public class AliPayTask {
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private IProductOrderService productOrderService;
    @Resource
    private IOrderService orderService;
    @Resource
    private OrderServiceImpl orderServiceImpl;
    /**
     * 每隔30秒查询一次未支付的订单
     */
    //@Scheduled(cron = "0/30 * * * * ?")
    public void orderConfirm(){
        //查询数据库中未支付的订单
        List<Order> orderList = orderMapper.selectList(new QueryWrapper<Order>().eq("state", 0));
        for (Order order : orderList) {
            String orderNo = order.getOrderNo();
            if(StrUtil.isBlank(orderNo)){
                throw new CommonException(201,"系统繁忙,稍后再试");
            }
            String result = orderService.queryOrder(orderNo);
            if(StrUtil.isNotBlank(result)){
                //1.将查询的json转为map
                Map map = JSON.parseObject(result, Map.class);
                Map dataMap = (Map) map.get("alipay_trade_query_response");
                String tradeNo = (String) dataMap.get("trade_no");
                String totalAmount = (String) dataMap.get("total_amount");
                //根据订单号查询List<CartDTO>
                List<CartDTO> cartDTOList=queryCartDTOList(orderNo);
                //根据订单号查询付款时间
                Date gmtPayment = queryGmtPayment(orderNo);
                orderServiceImpl.processOrder(cartDTOList,gmtPayment.toString(),tradeNo,orderNo);
            }
        }
    }

    /**
     * 根据订单号查询付款时间
     * @param orderNo
     * @return
     */
    private Date queryGmtPayment(String orderNo) {
        Order order = orderMapper.selectOne(new QueryWrapper<Order>().eq("order_no", orderNo));
        Date updateTime = order.getUpdateTime();
        return updateTime;
    }

    //根据订单号查询List<CartDTO>
    private List<CartDTO> queryCartDTOList(String orderNo) {
        Order order = orderMapper.selectOne(new QueryWrapper<Order>().eq("order_no", orderNo));
        if(Objects.isNull(order)){
            throw new CommonException(201,"系统繁忙,稍后再试");
        }
        Integer orderId = order.getId();
        List<ProductOrder> productOrderList = productOrderService.list(new QueryWrapper<ProductOrder>().eq("order_id", orderId));
        List<CartDTO> cartDTOList=new ArrayList<>();
        for (ProductOrder productOrder : productOrderList) {
            Integer productId = productOrder.getProductId();
            Long count = productOrder.getCount();
            CartDTO cartDTO = new CartDTO(productId,count.intValue());
            cartDTOList.add(cartDTO);
        }
        return cartDTOList;
    }
    
    

    
    
}
